import { StrTool } from './StrTool'

// noinspection JSUnusedGlobalSymbols
/**
 * FileTool
 * @author 冰凝
 * @date 2022-09-19 10:03:15
 **/
export class FileTool {

    /**
     * 截取文件名
     * @param url
     */
    public static getFilename(url?: string): string {
        if (StrTool.isEmpty(url)) {
            return StrTool.EMPTY
        }
        return url!.substring(url!.lastIndexOf(StrTool.PATH_INTEGRAL) + 1)
    }

    /**
     * 获取文件扩展名
     */
    public static getExpandedName(fileName?: string) {
        if (StrTool.isEmpty(fileName)) {
            return StrTool.EMPTY
        }
        const reg = new RegExp('^.*?(?<ext>\\.[^/]+)$')
        return reg.exec(fileName!)?.groups?.['ext'] ?? ''
    }

    /**
     * 指定 size < sizeTarget
     * @param {number} size 待判断字节数
     * @param {number} sizeTarget 目标大小
     * @param {FileSizeEnum} e sizeTarget 单位
     * @return {boolean} size < sizeTarget * e
     */
    public static lessThan(size: number, sizeTarget: number, e: FileSizeEnum): boolean {
        return size < sizeTarget * e
    }

    /**
     * 二进制文件转为 base64 编码对象
     */
    public static toBase64(file: Blob): Promise<string> {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => resolve(<string>reader.result)
            reader.onerror = (error) => reject(error)
        })
    }

}

/**
 * @see StorageUnit
 */
export enum FileSizeEnum {
    // noinspection JSUnusedGlobalSymbols
    KB = 1 << 10,
    MB = KB << 10,
    GB = MB << 10,
    TB = GB << 10,
}
